package bootstrap

import (
	"github.com/spf13/viper"
	"os"
	"path/filepath"
	"sdn-executor/config"
	"strings"
)

func InitConfig(configPath string, defaultConfigFile string, configFile string, configType string) (*config.Config, error) {
	var err error

	viper.AddConfigPath(configPath)
	viper.SetConfigType(configType)

	// 读取默认配置文件
	viper.SetConfigName(defaultConfigFile)
	if err = viper.ReadInConfig(); err != nil {
		return nil, err
	}

	existed, err := checkFileExists(configPath, configFile)
	if err != nil {
		return nil, err
	}
	if existed {
		viper.SetConfigName(configFile)
		if err = viper.MergeInConfig(); err != nil {
			return nil, err
		}
	}

	// 直接获取值
	// fmt.Println("cmd: ", viper.GetString("cmd"))

	err = viper.Unmarshal(config.C())
	if err != nil {
		return nil, err
	}

	return config.Conf, nil
}

func checkFileExists(dirPath string, fileName string) (bool, error) {
	files, err := os.ReadDir(dirPath)
	if err != nil {
		return false, err
	}

	for _, file := range files {
		name := strings.TrimSuffix(file.Name(), filepath.Ext(file.Name()))
		if !file.IsDir() && name == fileName {
			return true, nil
		}
	}
	return false, nil
}
